import React from 'react';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import Pagination from 'rc-pagination';
import pushCategoryAction from '../../actions/pushCategoryAction.js';
import Input from '../base/Input.js';
import Radio from '../base/RadioGroup.js';
import Widget from '../mui/Widget.js';
import SearchInput from '../mui/searchInput.js';

const pushCategory = withRouter(
  React.createClass({
    getInitialState() {
      return {
        buttonState: false,
        resData: '',
        pushList: [],
        name:'',
        seed_id: '',
        class_id: this.props.params.id
      };
    },
    componentDidMount() {
      const data = {
        keyword: '',
        page: 1,
        page_size: 15,
        env: 'test'
      };
      const { fetchPushCategoryList, getOneCategory, params } = this.props;
      fetchPushCategoryList(data);
      getOneCategory({ id: params.id });
    },
    componentWillReceiveProps(nextProps) {
      this.setState(
        {
          pushList: nextProps.CategoryList,
          resData: nextProps.pushCategoryList,
          seed_id: nextProps.checkedItem._id
        }
      );
      if (this.state.name && nextProps.checkedItem._id && !nextProps.saveMsg.data) {
        this.setState({ buttonState: true });
      } else {
        this.setState({ buttonState: false });
      }
      if (nextProps.saveMsg.code === 200) {
        this.setState({ visible: false });
      }
    },
    componentWillUnmount() {
      this.props.restorePushCategory();
    },
    handleName(targetData) {
      const { checkPackageName } = this.props;
      this.setState({ name: targetData.value });
      checkPackageName({ name: targetData.value, id: this.props.params.id });
      if (targetData.value && this.state.seed_id) {
        this.setState({ buttonState: true });
      } else {
        this.setState({ buttonState: false });
      }
    },
    handleSeedId(targetData) {
      const { saveMsg, storageChecked, getPushCategoryAction } = this.props;
      const { resData } = this.state;
      // const newPageList = [];
      // const updateObjIndex = pushList.findIndex((obj) =>
      //   obj._id === targetData.value
      // );
      // pushList.forEach((item, index) => {
      //   if (item.asMutable) {
      //     item.asMutable().checked = false;
      //     newPageList.push(item.asMutable());
      //   } else {
      //     item.checked = false;
      //     newPageList.push(item);
      //   }
      // });
      // newPageList[updateObjIndex].checked = true;
      // this.selectedItem = newPageList[updateObjIndex];
      storageChecked(targetData.value);
      getPushCategoryAction(resData);
      // this.setState({ pushList: newPageList, seed_id: targetData.value });
      if (this.state.name && !saveMsg.data) {
        this.setState({ buttonState: true });
      } else {
        this.setState({ buttonState: false });
      }
    },
    savePushCategory() {
      const { savePushCategory, checkPackageName, saveMsg, router } = this.props;
      checkPackageName({ name: this.state.name, id: this.props.params.id });
      if (saveMsg.data) {
        return;
      }
      const data = {
        name: this.state.name,
        seed_id: this.state.seed_id,
        class_id: this.props.params.id
      };
      savePushCategory(data, router);
    },
    search(target) {
      this.searchValue = target.value;
      const data = {
        keyword: target.value,
        page_size: 15,
        env: 'test'
      };
      const { fetchPushCategoryList } = this.props;
      fetchPushCategoryList(data);
    },
    pagination(pageNumber) {
      const data = {
        page: pageNumber,
        page_size: 15,
        keyword: this.searchValue,
        env: 'test'
      };
      const { fetchPushCategoryList } = this.props;
      fetchPushCategoryList(data);
    },

    render() {
      const { pushList, buttonState } = this.state;
      const { saveMsg, pushCategoryList, oneCategoryData } = this.props;
      const button = <button className="btn btn-primary" key="close" onClick={this.savePushCategory}>推送至此类</button>;
      const disableButton = <button className="btn btn-disable" key="close" disabled="disabled">推送至此类</button>;
      return (
        <div>
          <Widget widgetHeader={'测试类列表'} widgetHeaderTwo={'推送至此类'} />
          <div className="widget-body">
            <div className="title-button-group">
              <span className="btn btn-message">
                <span className="max-font" title={oneCategoryData.name}>{oneCategoryData.name}</span>
              </span>
              {buttonState ? button : disableButton}
            </div>
            <div className="form-group push-name-input">
              <label className="control-label w100" htmlFor="version">此次推送命名</label>
              <div className="input-group w560">
                <Input
                  data-target="name"
                  type="text"
                  onChange={this.handleName}
                  value={this.state.name}
                  placeholder="(必填，不可重复)"
                  maxLength={128}
                />
              </div>
              {saveMsg.data ? <span className="mr10 text-danger">命名重复，请重新输入</span> : ''}
            </div>
            <SearchInput placeholder={"包命名"} onSearch={this.search} className={'search-category mb20'} />
            <Widget widgetHeader={'选择测试包'} />
            <table className="table table-hover">
              <thead>
                <tr>
                  <th className="mw90">操作</th>
                  <th className="mw490">包命名</th>
                  <th className="mw490">备注</th>
                </tr>
              </thead>
              <tbody>
                  {
                    pushList.map((item, index) =>
                      <tr key={item._id} className={item.checked ? 'bg-color-f6' : ''}>
                        <td>
                          <Radio
                            name={'seed_id'}
                            data-value={item}
                            onClick={this.handleSeedId}
                            data-target={'seed_id'}
                            defaultChecked={item.checked}
                          />
                        </td>
                        <td>{item.name}</td>
                        <td>{item.remark}</td>
                      </tr>
                    )
                  }
              </tbody>
            </table>
            {!pushList.length ? <p className="no-data-message">搜索无结果</p> : ''}
            <div className="push-pagination">
              <Pagination
                className="ant-pagination"
                defaultCurrent={1}
                current={pushCategoryList.page}
                total={pushCategoryList.pages ? pushCategoryList.pages * 10 : 0}
                onChange={this.pagination}
              />
            </div>
          </div>
        </div>
      );
    }
  })
);

const mapStateToProps = function (state) {
  return {
    pushCategoryList: state.pushCategory.pushCategoryList,
    CategoryList: state.pushCategory.CategoryList,
    saveMsg: state.pushCategory.saveMsg,
    checkedItem: state.pushCategory.checkedItem,
    oneCategoryData: state.testCategory.oneCategoryData
  };
};

module.exports = connect(mapStateToProps, pushCategoryAction)(pushCategory);
// export default pushCategoryList;
